package per.wsj.observer

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import per.wsj.observer.databinding.ActivityMainBinding
import android.widget.Toast

import per.wsj.observer.JniUtil.mmapSetEmpty

import android.text.TextUtils

import per.wsj.observer.JniUtil.observe

import android.os.Environment
import android.util.Log
import java.lang.Exception


class MainActivity : AppCompatActivity() {

    private var isObserve = false

    private val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.btOpen.setOnClickListener { v ->
            val path = externalCacheDir!!.absolutePath + "/mmaptest.txt"
            JniUtil.mmapOpen(path)
        }
        binding.btClose.setOnClickListener { v ->
            isObserve = false
            JniUtil.mmapClose()
            Toast.makeText(this, "关闭并停止监听", Toast.LENGTH_SHORT).show()
        }
        binding.btObserve.setOnClickListener { v ->
            if (isObserve) return@setOnClickListener
            isObserve = true
            //开线程每隔500毫秒获取一下共享映射区的内容
            Thread {
                while (isObserve) {
                    try {
                        val observe = observe("")
                        Log.e("MainActivity", "observe: $observe")
                        //当我们监听到共享区的内容不为空的时候就将内容以Toast的方式显示出来
                        if (!TextUtils.isEmpty(observe)) {
                            runOnUiThread {
                                Toast.makeText(this, observe, Toast.LENGTH_SHORT).show()
                            }
                            //获取完之后将共享区内容置空
                            mmapSetEmpty()
                        }
                        Thread.sleep(1000)
                    } catch (e: Exception) {
                        Log.e("MainActivity", "err: $e")
                    }
                }
            }.start()
            Toast.makeText(this, "开始监听", Toast.LENGTH_SHORT).show()
        }
    }
}